/**
 * 
 */
package fhq.hcmute.edu.vn.util;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

/**
 * @author nglehien Nov 12, 2012 - 5:39:38 PM
 */
public class Powerpoint {
	private File file;
	FileInputStream is;
	private Object ppt;
	private Object[] slides;
	private Dimension pgsize;

	public Powerpoint(File file) throws IOException {
		this.file = file;
		is = new FileInputStream(file);
		if (file.getName().endsWith("ppt")) {
			ppt = new SlideShow(is);
			pgsize = ((SlideShow) ppt).getPageSize();
			slides = ((SlideShow) ppt).getSlides();
		} else if (file.getName().endsWith("pptx")) {
			ppt = new XMLSlideShow(is);
			pgsize = ((XMLSlideShow) ppt).getPageSize();
			slides = ((XMLSlideShow) ppt).getSlides();
		}
	}

	public int getSlideCount() {
		return slides.length;
	}

	public void saveSlide(Object slide, String name) throws IOException {
		BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,
				BufferedImage.TYPE_INT_ARGB);
		Graphics2D graphics = img.createGraphics();
		graphics.setPaint(Color.white);
		graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

		if (slide instanceof Slide) {
			((Slide) slide).draw(graphics);
		} else if (slide instanceof XSLFSlide) {
			((XSLFSlide) slide).draw(graphics);
		}
		String path = "/Powerpoint/" + file.getName();
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		path += "/" + name + ".png";
		FileOutputStream out = new FileOutputStream(path);
		javax.imageio.ImageIO.write(img, "png", out);
		out.close();
	}

	public void convert() throws Exception {
		for (int i = 0; i < slides.length; i++) {
			saveSlide(slides[i], "Slide_" + i);
		}
	}
}
